<template>
  <div style="height: 100%">
    <fks-query-page
      :id="id"
      v-loading="loading"
      :current-page.sync="currentPage"
      :page-size.sync="pageSize"
      :page-sizes="[20, 50, 100]"
      :total="total"
      :data="tableData"
      :table-name="tableName"
      layout="total,sizes,prev,pager,next,jumper"
      @query="refreshTable"
      @sort-change="sortHandler"
    >
      <template slot="singleSearch">
        <div class="single-searchBox">
          <fks-input
            v-model="keywords"
            size
            class="single-searchBox-item"
            clearable
            maxlength="50"
            :placeholder="LANG.NAME_OR_CODE"
            @keyup.native.enter="search"
            @clear="search"
          >
            <fks-button slot="append" icon="fks-icon-search" @click="search" />
          </fks-input>
          <fks-button @click="openDialog">
            <i class="fks-icon-import" />
            {{ LANG.IMPORT }}
          </fks-button>
          <fks-button
            v-permission="['i18n:item:add']"
            type="primary"
            icon="fks-icon-plus"
            style="float: right"
            @click="addRow"
          >
            {{ LANG.ADD }}
          </fks-button>
        </div>
      </template>
      <template>
        <fks-table-column type="index" label="#" width="60" align="center" />
        <fks-table-column
          sortable="custom"
          :label="LANG.CODE"
          prop="code"
          align="left"
          header-align="center"
          min-width="100"
        >
          <template slot-scope="scope">
            <div
              :style="{
                color: scope.row.remark === 'online' ? 'red' : 'blue'
              }"
            >
              {{ scope.row.code }}
            </div>
          </template>
        </fks-table-column>
        <fks-table-column
          prop="content"
          align="left"
          header-align="center"
          :render-header="langSelect"
          header-cell-class-name="select-lang"
          min-width="200"
        >
          <template slot-scope="scope">
            <div
              :style="{
                color: scope.row.remark === 'online' ? 'red' : 'blue'
              }"
            >
              {{ scope.row.content }}
            </div>
          </template>
        </fks-table-column>
        <fks-table-column :label="LANG.OPERATION" width="100" align="left">
          <span slot-scope="scope">
            <fks-button
              v-permission="['i18n:item:edit']"
              type="text"
              @click="showDetail(scope.row)"
              >{{ LANG.EDIT }}</fks-button
            >
            <fks-button
              v-permission="['i18n:item:delete']"
              danger-text
              @click="del(scope.row.code)"
              >{{ LANG.DELETE }}</fks-button
            >
          </span>
        </fks-table-column>
      </template>
    </fks-query-page>
    <dragtable
      :visible.sync="dialogVisible"
      :module-code="tableCode"
      :type="type"
      :data="rowData"
    />
    <fks-dialog :visible.sync="importVisible" width="960px" @close="close">
      <template slot="title">
        <i class="fks-icon-import" />
        <span>{{ LANG.IMPORT_LOCAL_LANG }}</span>
      </template>
      <fks-table
        v-loading="currentDetailLoading"
        height="360"
        :data="localTable"
        @selection-change="handleSelectionChange"
      >
        <fks-table-column type="selection" width="55" />
        <fks-table-column type="index" label="#" width="60" align="center" />
        <fks-table-column :label="LANG.CODE" prop="code" />
        <fks-table-column :label="LANG.NAME" prop="content" />
      </fks-table>
      <span slot="footer" class="dialog-footer">
        <fks-button
          type="primary"
          icon="fks-icon-check"
          @click="importSubmit"
          >{{ LANG.SAVE }}</fks-button
        >
      </span>
    </fks-dialog>
  </div>
</template>

<script>
import Mix from '@/mixins/module'
import Dragtable from './Dragtable'
import {
  getAllDetail,
  getCurrentDetail,
  deleteDetail,
  addLangDetail
} from '../../api/common'
import langEdit from './langEdit'
import { ENUM } from '@/store/State/stateTypes'
export default {
  name: 'LangEdit',
  components: {
    Dragtable
  },
  mixins: [langEdit],
  data() {
    return {
      loading: true,
      type: 'add', //对话框打开时状态
      dialogVisible: false,
      showDialog: true,
      keyDetail: {}, //某一key下的全部语言内容
      pageSize: 20,
      total: 0,
      currentPage: 1,
      langData: {},
      tableData: [],
      menuData: [], //菜单分栏
      langg: {},
      currentLang: '',
      rowData: [],
      sort: '',
      importVisible: false,
      currentDetailLoading: false, //本地多语言表格loading
      currentDetail: [], //当前键值对应不分页数据
      localLangList: [], //读出的本地多语言列表数据
      localLang: [], //选中需要导入的本地多语言列表
      localTable: [] //导入本地多语言弹框表格数据
    }
  },
  computed: {
    languages() {
      return this.$store.state[ENUM].languages || []
    }
  },
  watch: {
    currentLang(newVal, oldVal) {
      if (oldVal != '') {
        this.refreshTable()
      }
    },
    $lang(val) {
      this.currentLang = this.$lang
    }
  },
  mounted() {
    this.currentLang = this.$lang
  },
  methods: {
    //排序
    sortHandler(data) {
      let params = {}
      if (!data.order) {
        this.sort = ''
      } else {
        this.sort = data.order == 'ascending' ? 'asc' : 'desc'
      }
      params = {
        langCode: this.currentLang,
        id: this.id,
        code: this.keywords,
        page: this.currentPage,
        size: this.pageSize,
        sort: this.sort
      }
      this.getDataList(params)
    },
    //删除code
    del(val) {
      this.$confirm(this.LANG.DELETE_KEY, this.LANG.TIPS, {
        title: this.LANG.DELETE,
        confirmButtonText: this.LANG.DELETE,
        cancelButtonText: this.LANG.CANCEL,
        deleteMode: true
      })
        .then(() => {
          let params = {
            id: this.id,
            code: val
          }
          deleteDetail(params)
            .then((res) => {
              if (res.status) {
                this.refreshTable()
                this.$message.success(this.LANG.DELETE_SUCCESS)
              }
            })
            .catch(() => {})
        })
        .catch(() => {})
    },
    //更新表格
    refreshTable() {
      if (!this.keywords) {
        let params = {
          id: this.id,
          langCode: this.currentLang,
          page: this.currentPage,
          size: this.pageSize,
          sort: this.sort
        }
        this.getDataList(params)
      } else {
        this.getModules()
      }
    },
    //表格头语种切换
    langSelect(h, { column, $index }) {
      // 给表格添加包裹的div
      return h('div', {}, [
        // 添加fks-select 标签
        h(
          'fks-select',
          {
            on: {
              input: (value) => {
                this.currentLang = value
              }
            },
            props: {
              value: this.currentLang, // 给fks-select 设置值（也是相当于v-model）
              size: 'small',
              'popper-class': 'select-lang',
              style: {
                height: '25px',
                width: '120px',
                paddingLeft: '0px',
                paddingRight: '0px'
              }
            }
          },
          [
            //给当前 fks-select 设置 fks-option
            this.languages.map((item) => {
              return h('fks-option', {
                props: {
                  value: item.code,
                  label: item.name
                }
              })
            })
          ]
        )
      ])
    },
    showDetail(row) {
      this.type = 'edit'
      this.rowData = row
      this.dialogVisible = true
    },
    //关闭导入多语言弹窗
    close() {
      this.importVisible = false
      this.currentDetailLoading = false
      this.currentDetail = []
      // this.localLangList = []
      this.localLang = []
      this.localTable = []
    },
    //打开导入本地多语言弹窗
    openDialog() {
      this.importVisible = true
      this.currentDetailLoading = true
      this.importLang()
    },
    //读取本地多语言
    getLocalLang() {
      this.localLangList = []
      if (/G_/.test(this.tableCode)) {
        let tempCode = '/' + this.tableCode.replace('G_', '') + '.js'
        let reg = new RegExp(tempCode, 'i')
        let reqs = require.context('@/lang', true, /\.js$/)
        reqs.keys().forEach((key) => {
          if (reg.test(key)) {
            let tempObj = reqs(key).default
            let tempKeys = Object.keys(tempObj) || []
            let tempVals = Object.values(tempObj) || []
            tempKeys.forEach((key, index) => {
              let obj = {
                code: key,
                content: tempVals[index],
                parentId: this.id,
                langCode: 'zh-CN'
              }
              this.localLangList.push(obj)
            })
          }
          reqs(key).default
        })
      } else {
        const locale = sessionStorage.getItem('locale') || '[]'
        let modules = JSON.parse(locale)
        modules.forEach((key) => {
          let regStr = '/' + this.tableCode + '/lang.js'
          if (key.match(regStr) == regStr) {
            let tempObj = require(`@/${key.substring(2, key.length - 3)}.js`)
              .default
            let tempKeys = Object.keys(tempObj) || []
            let tempVals = Object.values(tempObj) || []
            tempKeys.forEach((key, index) => {
              let obj = {
                code: key,
                content: tempVals[index],
                parentId: this.id,
                langCode: 'zh-CN'
              }
              this.localLangList.push(obj)
            })
          }
        })
      }
    },
    //筛选本地多余的和线上多余的多语言编码
    filterData() {
      for (let i = 0; i < this.localLangList.length; i++) {
        for (let j = 0; j < this.currentDetail.length; j++) {
          if (this.localLangList[i].code == this.currentDetail[j].code) {
            this.localLangList.splice(i, 1)
            this.currentDetail.splice(j, 1)
            i--
            j--
            break
          }
        }
      }
    },
    importLang() {
      this.localTable = JSON.parse(JSON.stringify(this.localLangList))
      this.currentDetailLoading = false
    },
    //选中本地多语言列表事件
    handleSelectionChange(val) {
      this.localLang = val
    },
    //提交选中的本地多语言
    importSubmit() {
      addLangDetail(this.localLang)
        .then((res) => {
          if (res.status) {
            this.$message.success(this.LANG.ADD_SUCCESS)
            this.importVisible = false
            let params = {
              id: this.id,
              langCode: 'zh-CN',
              page: this.currentPage,
              size: this.pageSize,
              sort: this.sort
            }
            this.getDataList(params)
          }
        })
        .catch((err) => {})
    },
    addRow(row) {
      this.type = 'add'
      this.rowData = { parentId: this.id }
      this.dialogVisible = true
    },
    getModules() {
      let params = {
        langCode: this.currentLang,
        id: this.id,
        code: this.keywords,
        page: this.currentPage,
        size: this.pageSize,
        sort: this.sort
      }
      this.getDataList(params)
    },
    search() {
      let params = {
        langCode: this.currentLang,
        id: this.id,
        code: this.keywords,
        page: 1,
        size: this.pageSize,
        sort: this.sort
      }
      this.getDataList(params)
    },
    getDataList(params) {
      getAllDetail(params)
        .then((res) => {
          if (res.status) {
            this.langData = { ...res.data.list }
            this.total = res.data.total
            this.transToTableData()
          }
        })
        .catch(() => {})
    },
    /**
     * @description: 将资源数据转为表格所需数据
     * @param {type}
     * @return:
     */
    transToTableData() {
      let params = {
        langCode: 'zh-CN',
        id: this.id,
        sort: 'asc'
      }
      getCurrentDetail(params)
        .then((res) => {
          if (res.status) {
            this.currentDetail = res.data
            this.getLocalLang()
            this.filterData()
            this.tableData = []
            for (var a in this.langData) {
              this.tableData = this.tableData.concat(this.langData[a])
            }
            for (let i = 0; i < this.tableData.length; i++) {
              for (let j = 0; j < this.currentDetail.length; j++) {
                if (this.tableData[i].code == this.currentDetail[j].code) {
                  this.tableData[i].remark = 'online'
                  break
                } else {
                  this.tableData[i].remark = ''
                }
              }
            }
            this.loading = false
          }
        })
        .catch((err) => {
          this.tableData = []
          this.loading = false
        })
    },
    /**
     * @description: 将表格数据转为上传数据
     * @param {type}
     * @return:
     */
    transToLangData() {
      this.languages.forEach((lang) => {
        let temp = {}
        for (let item of this.tableData) {
          if (item.key) {
            temp[item.key] = item[lang.code]
          }
        }
        for (let item of this.menuData) {
          if (item.key) {
            temp[item.key] = item[lang.code]
          }
        }
        this.langData[lang.code] = JSON.stringify(temp)
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import './langEdit.scss';
</style>
